$(function(){
  // 所有代码写在这里，否则会发生不执行js的情况
  $(document).on('pageInit', '#page-recipe', function (e, id, page) {
    console.log('page-recipe init');

    // 性别默认值
    $('#sex').on('change', function() {
      var val = $(this).val();
      if (val === '0') { // 男
        $('#height').val('170');
        $('#weight').val('65');
      }
      if (val === '1') { // 女
        $('#height').val('160');
        $('#weight').val('55');
      }
    });

    // 劳动强度弹窗说明
    $(document).on('click', '.j-showLaborExplain', function() {
      $.modal({
        
        text: '\
          <p style="text-align:left">轻体力劳动 : 做家务、教师、办公室人员、售货员等</p>\
          <p style="text-align:left">中体力劳动 : 学生、司机、车间工人等</p>\
          <p style="text-align:left">重体力劳动 : 农民、搬运工、建筑工、装卸工、矿工等</p>\
        ',
        buttons: [
          {
            text: '确定'
          }
        ]
      });
    });


    // 表单验证
    $(document).on('click', '.j-submit', function () {

      var sex          = $('#sex'),
          year         = $('#year'),
          height       = $('#height'),
          weight       = $('#weight'),
          exercise     = $('#exercise'),
          status       = $('#status'),
          sex_val      = $('#sex').val(),
          year_val     = $('#year').val(),
          height_val   = $('#height').val(),
          weight_val   = $('#weight').val(),
          exercise_val = $('#exercise').val(),
          status_val   = $('#status').val(),
          age,
          bmi, // 体重/身高
          shape, // 体型 (0|-1|1)
          energy, // 所需能量
          result; // 能量范围获取


      if (!sex_val) {
        $.toast('请选择性别');
        setError(sex);
        return;
      }
      if (!year_val) {
        $.toast('请选择出身年份');
        setError(year);
        return;
      }
      if (!height_val) {
        $.toast('请选择身高');
        setError(height);
        return;
      }
      if (!weight_val) {
        $.toast('请选择体重');
        setError(weight);
        return;
      }
      if (!exercise_val) {
        $.toast('请选择活动量');
        setError(exercise);
        return;
      }
      if (!status_val) {
        $.toast('请选择并发症');
        setError(status);
        return;
      }

      if (status_val !== '0') {
        $.alert('有并发症患者请咨询医生');
        return;
      }

      // 转换成数字类型，为什么不在验证之前写呢？因为有的值为0，也会判定为假
      sex_val      = sex_val - 0,
      year_val     = year_val - 0,
      height_val   = height_val / 100,
      weight_val   = weight_val - 0,
      exercise_val = exercise_val - 0,
      status_val   = status_val - 0,

      age = new Date().getFullYear() - year_val;
      bmi = (weight_val / (height_val * height_val)).toFixed(1);

      if (bmi >= 18.5 && bmi <= 24) {
        shape = 0;
        /*$.toast('您的体型正常!');*/
      }

      if (bmi < 18.5) {
        shape = -1;
        /*$.toast('您的体型偏瘦!');*/
      }

      if (bmi > 24) {
        shape = 1;
        /*$.toast('您的体型偏重!');*/
      }

      switch (exercise_val) {
        case 0:
          if (shape == 0) {
            energy = weight_val * 20;
          }
          if (shape == 1) {
            energy = weight_val * 15;
          }
          if (shape == -1) {
            energy = weight_val * 25;
          }
          break;
        case 1:
          if (shape == 0) {
            energy = weight_val * 30;
          }
          if (shape == 1) {
            energy = weight_val * 25;
          }
          if (shape == -1) {
            energy = weight_val * 35;
          }
          break;
        case 2:
          if (shape == 0) {
            energy = weight_val * 35;
          }
          if (shape == 1) {
            energy = weight_val * 30;
          }
          if (shape == -1) {
            energy = weight_val * 40;
          }
          break;
        case 3:
          if (shape == 0) {
            energy = weight_val * 40;
          }
          if (shape == 1) {
            energy = weight_val * 35;
          }
          if (shape == -1) {
            energy = weight_val * 50;
          }
          break;
      }

      if (energy < 1100) {
        $.alert('抱歉，暂时没有计算出您的食谱');
        return;
      }

      if (energy >= 1100 && energy < 1125) {
        result = 1100;
      }
      if (energy >= 1125 && energy < 1150) {
        result = 1125;
      }
      if (energy >= 1150 && energy < 1175) {
        result = 1150;
      }
      if (energy >= 1175 && energy < 1200) {
        result = 1175;
      }
      if (energy >= 1200 && energy < 1250) {
        result = 1200;
      }
      if (energy >= 1250 && energy < 1275) {
        result = 1250;
      }
      if (energy >= 1275 && energy < 1300) {
        result = 1275;
      }
      if (energy >= 1300 && energy < 1376) {
        result = 1300;
      }
      if (energy >= 1376 && energy < 1406) {
        result = 1376;
      }
      if (energy >= 1406 && energy < 1425) {
        result = 1406;
      }
      if (energy >= 1425 && energy < 1406) {
        result = 1425;
      }
      if (energy >= 1406 && energy < 1425) {
        result = 1406;
      }
      if (energy >= 1425 && energy < 1475) {
        result = 1425;
      }
      if (energy >= 1475 && energy < 1495) {
        result = 1475;
      }
      if (energy >= 1495 && energy < 1504) {
        result = 1495;
      }
      if (energy >= 1504 && energy < 1520) {
        result = 1504;
      }
      if (energy >= 1520 && energy < 1550) {
        result = 1520;
      }
      if (energy >= 1550 && energy < 1605) {
        result = 1550;
      }
      if (energy >= 1605 && energy < 1650) {
        result = 1605;
      }
      if (energy >= 1650 && energy < 1700) {
        result = 1650;
      }
      if (energy >= 1700 && energy < 1750) {
        result = 1700;
      }
      if (energy >= 1750 && energy < 1850) {
        result = 1750;
      }
      if (energy >= 1850 && energy < 2000) {
        result = 1850;
      }
      if (energy >= 2000) {
        result = 2000;
      }

      console.log('bmi:' + bmi + '   energy:' + energy + '   result:' + result);

      $.showPreloader('正在生成您的食谱...');
      $.ajax({
        url: 'data/data.json',
        type: 'GET',
        dataType: 'json',
        data: {},
      })
      .done(function(data) {
        $.hidePreloader();

        var _html = $("\
          <div class=m-result-item>\
            <div class=tit>一日三餐</div>\
            <div class=subTit>早餐</div>\
            "+ arr2html(data[result].food.breakfast) +"\
          </div>\
          <div class=m-result-item>\
            <div class=subTit>中餐</div>\
            "+ arr2html(data[result].food.lunch) +"\
          </div>\
          <div class=m-result-item>\
            <div class=subTit>晚餐</div>\
            "+ arr2html(data[result].food.dinner) +"\
          </div>\
          <div class=m-result-item>\
            <div class=subTit>全日摄入总热量</div>\
            <div class=txt>"+ data[result].food.proportion.heat +"</div>\
          </div>\
          <div class=m-result-item>\
            <div class=subTit>氮:总热量</div>\
            <div class=txt>"+ data[result].food.proportion.nitrogen_heat +"</div>\
          </div>\
          <table class='m-table border _a'>\
            <tr class='border _b'>\
              <td class='border _r'></td>\
              <td class='border _r'>碳水化合物</td>\
              <td class='border _r'>蛋白质</td>\
              <td>脂肪</td>\
            </tr>\
            <tr class='border _b'>\
              <td class='border _r'>实际重量（克）</td>\
              <td class='border _r'>"+ data[result].food.proportion.carbohydrate.weight +"</td>\
              <td class='border _r'>"+ data[result].food.proportion.protein.weight +"</td>\
              <td>"+ data[result].food.proportion.fat.weight +"</td>\
            </tr>\
            <tr>\
              <td class='border _r'>占总热量（%）</td>\
              <td class='border _r'>"+ data[result].food.proportion.carbohydrate.proportion +"</td>\
              <td class='border _r'>"+ data[result].food.proportion.protein.proportion +"</td>\
              <td>"+ data[result].food.proportion.fat.proportion +"</td>\
            </tr>\
          </table>\
          <div class=m-result-item>\
            <div class=subTit>"+ data[result].footDetail.breakfast.title +"</div>\
            "+ arr2html(data[result].footDetail.breakfast.content) +"\
          </div>\
          <div class=m-result-item>\
            <div class=subTit>"+ data[result].footDetail.lunch_dinner.title +"</div>\
            "+ arr2html(data[result].footDetail.lunch_dinner.content) +"\
            "+ arr2html(data[result].footDetail.lunch_dinner.tip) +"\
          </div>\
          <div class=m-result-item>\
            <div class=tit>糖尿病饮食禁忌</div>\
            <div class=subTit>"+ data[result].taboo.title +"</div>\
            "+ arr2html(data[result].taboo.content) +"\
          </div>\
          <div class=m-result-item>\
            <div class=subTit>"+ data[result].caution.title +"</div>\
            "+ arr2html(data[result].caution.content) +"\
          </div>\
          <div class=m-result-item>\
            <div class=subTit>"+ data[result].daily.title +"</div>\
            "+ arr2html(data[result].daily.content) +"\
          </div>\
        ");

        $('#page-result .m-result').html(_html);

        $.router.loadPage("#page-result", true);
      })
      .fail(function(error) {
        $.hidePreloader();
        $.toast('服务器连接异常');
        console.log(error);
      });
      
    });
    // 表单验证结束

    function setError(obj) {
      obj.parents('.item-inner').find('.item-title').css({color: 'red'});
    }

    function arr2html(arr) {
      var i    = 0,
          len  = arr.length,
          html = "<ul>";

      for (; i < len; i++) {
        html += "<li class=txt>" + arr[i] + "</li>";
      }

      html += '</ul>';

      return html;
    }

    $(document).on('click', '.item-input', function() {
      $(this).parents('.item-inner').find('.item-title').css({color: 'inherit'});
    });

  });
  
  $(document).on('pageReinit', '#page-recipe', function (e, id, page) {
    console.log('page-recipe pageReinit');
    $('#sex').val('0');
    $('#year').val('');
    $('#height').val('170');
    $('#weight').val('60');
    $('#exercise').val('1');
    $('#status').val('0');
  });

  $(document).on('pageInit', '#page-result', function (e, id, page) {
    console.log('page-result init');
  });

  $(document).on('pageReinit', '#page-result', function (e, id, page) {
    console.log('page-result pageReinit');
  });

  $.init();
});